package com.sum.tea.rongrui.viewmodel

import kotlinx.coroutines.withContext
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.*
import com.blankj.utilcode.util.ConvertUtils
import com.example.lib_rongrui.RrReader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

class FSTViewModel : ViewModel() {

    private val _result = MutableLiveData<String>()
    val result: LiveData<String> = _result

    private val _buttonsEnabled = MutableLiveData<Boolean>().apply { value = true }
    val buttonsEnabled: LiveData<Boolean> = _buttonsEnabled

    private var tranData: ByteArray? = null

    private val handler = Handler(Looper.getMainLooper())

    private var mThread: Thread? = null

    fun setTranData(data: ByteArray) {
        tranData = data
    }

    fun sendMessage(msgData: String, mType: Int) {
        val simpleDateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        val date = Date(System.currentTimeMillis())
        val textLog = "${simpleDateFormat.format(date)} $msgData"
        when (mType) {
            0x01 -> _result.value = textLog
            0x02 -> {
                _buttonsEnabled.value = true
            }
            // 处理其他类型消息
        }
    }

    fun loadEPCData() {
        viewModelScope.launch(Dispatchers.IO) {
//            val epcList = ScanModeActivity.mlist
//            val epcData = epcList.toTypedArray()
            withContext(Dispatchers.Main) {
                // 假设有一个引用到Spinner的LiveData或通过Activity更新
                // 这里需要通过Activity或其他方式更新Spinner的数据
            }
        }
    }

    fun transImage() {
        viewModelScope.launch {
            if (tranData == null || tranData!!.size != 4736) {
                sendMessage("没有选择文件", 0x01)
                return@launch
            }
            if (mThread == null) {
                _buttonsEnabled.value = false
                mThread = Thread {
                    val success = tranImage()
                    if (success) {
                        sendMessage("文件传输成功", 0x01)
                    } else {
                        sendMessage("文件传输失败", 0x01)
                    }
                    handler.post {
                        sendMessage("", 0x02)
                        mThread = null
                    }
                }
                mThread?.start()
            }
        }
    }

    fun showImage(epcString: String?) {
        viewModelScope.launch {
            if (mThread == null) {
                _buttonsEnabled.value = false
                val epc = epcString?.takeIf { it.isNotEmpty() }?.let { ConvertUtils.hexString2Bytes(it) }
                mThread = Thread {
                    sendMessage("等待命令执行", 0x01)
                    val eNum = (epc?.size ?: 0) / 2
                    val result = RrReader.rrlib.FST_ShowImage(eNum.toByte(), epc)
                    if (result == 0) {
                        sendMessage("命令执行成功", 0x01)
                    } else {
                        sendMessage("命令执行失败", 0x01)
                    }
                    handler.post {
                        sendMessage("", 0x02)
                        mThread = null
                    }
                }
                mThread?.start()
            }
        }
    }

    private fun tranImage(): Boolean {
        tranData?.let { data ->
            val startAdd = ByteArray(2)
            for (m in 0 until 23) {
                val chunk = data.copyOfRange(m * 200, (m + 1) * 200)
                startAdd[0] = ((200 * m) shr 8).toByte()
                startAdd[1] = ((200 * m) and 255).toByte()
                var success = false
                for (n in 0 until 3) {
                    val result = RrReader.rrlib.FST_TranImage(200.toByte(), startAdd, chunk)
                    if (result == 0) {
                        success = true
                        val progress = ((m + 1) * 100) / 24
                        sendMessage("文件已传输: ${progress}％", 0x01)
                        break
                    }
                }
                if (!success) {
                    return false
                }
            }

            // 最后136字节
            val lastChunk = data.copyOfRange(4600, 4736)
            startAdd[0] = (4600 shr 8).toByte()
            startAdd[1] = (4600 and 255).toByte()
            var success = false
            for (n in 0 until 3) {
                val result = RrReader.rrlib.FST_TranImage(136.toByte(), startAdd, lastChunk)
                if (result == 0) {
                    success = true
                    sendMessage("文件已传输: 100％", 0x01)
                    break
                }
            }
            return success
        }
        return false
    }
}
